package by.amakarevich.dataaccess.Impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.amakarevich.dataaccess.TambourDao;
import by.amakarevich.datamodel.Product;
import by.amakarevich.datamodel.Tambour;
import by.amakarevich.datamodel.Tambour_;

@Repository
public class TambourDaoImpl extends AbstractDaoImpl<Long, Tambour> implements TambourDao {
	protected TambourDaoImpl(){
		super(Tambour.class);
	}
	
	@Override
	public List<Tambour> getAllTambour(){
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<Tambour> criteria = cBuilder.createQuery(Tambour.class);
        Root<Tambour> root = criteria.from(Tambour.class);

        criteria.select(root);
        root.fetch(Tambour_.product);
        criteria.distinct(true);
        

        TypedQuery<Tambour> query = getEm().createQuery(criteria);
        List<Tambour> results = query.getResultList();
        return results;
	}
	@Override
	public Tambour getByProductId(Product product){
		  CriteriaBuilder cBuilder= getEm().getCriteriaBuilder();
		  CriteriaQuery<Tambour> criteria=cBuilder.createQuery(Tambour.class);
		  Root<Tambour> root=criteria.from(Tambour.class);
		  
		  criteria.select(root);
	      root.fetch(Tambour_.product);
	      criteria.distinct(true);
		  criteria.where(cBuilder.equal(root.get(Tambour_.product),product.getId()));

		  TypedQuery<Tambour> query = getEm().createQuery(criteria);
		  Tambour results = (Tambour)query.getSingleResult();
	      return results;
	}
}
